package com.chain.BrotherExchange.ui.fragment;

import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.AnnouncementList;
import com.chain.BrotherExchange.data.model.BannerList;
import com.chain.BrotherExchange.data.model.UserAssets;
import com.chain.BrotherExchange.event.LoginEvent;
import com.chain.BrotherExchange.event.LogoutEvent;
import com.chain.BrotherExchange.event.UserAssetsChangeEvent;
import com.chain.BrotherExchange.event.UserAssetsVisibilityEvent;
import com.chain.BrotherExchange.event.UserPortraitChangeEvent;
import com.chain.BrotherExchange.ui.activity.LoginActivity;
import com.chain.BrotherExchange.ui.adapter.ImageAdvertsAdapter;
import com.chain.BrotherExchange.ui.adapter.QuotationListAdapter;
import com.chain.BrotherExchange.ui.core.BaseFragment;
import com.chain.BrotherExchange.utils.ActivityBarHelper;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.utils.CycleAdverts;
import com.chain.BrotherExchange.utils.ImageViews;
import com.chain.BrotherExchange.viewmodel.HomeViewModel;
import com.chain.BrotherExchange.viewmodel.PersonalCenterViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;
import com.chain.BrotherExchange.widget.GalleryLayoutManager;
import com.chain.BrotherExchange.widget.transformer.ScaleTransformer;
import com.example.common.widget.state.NetworkStateLayout;

import org.greenrobot.eventbus.Subscribe;

import butterknife.Bind;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

public class HomeFragment extends BaseFragment {

    @Bind(R.id.login_view) View mLoginView;
    @Bind(R.id.root_layout) ViewGroup mRootLayout;
    @Bind(R.id.adverts_list) RecyclerView mAdvertsList;
    @Bind(R.id.home_login_layout) View mHomeLoginLayout;
    @Bind(R.id.user_assets_layout) View mUserAssetsLayout;
    @Bind(R.id.coin_assets_text) TextView mCoinAssetsText;
    @Bind(R.id.performer_list) RecyclerView mPerformerList;
    @Bind(R.id.total_assets_text) TextView mTotalAssetsText;
    @Bind(R.id.announcement_layout) View mAnnouncementLayout;
    @Bind(R.id.user_avatar_image) ImageView mUserAvatarImage;
    @Bind(R.id.daily_turnover_text) TextView mDayTurnoverText;
    @Bind(R.id.week_turnover_text) TextView mWeekTurnoverText;
    @Bind(R.id.month_turnover_text) TextView mMonthTurnoverText;
    @Bind(R.id.coin_assets_cny_text) TextView mCoinAssetsCnyText;
    @Bind(R.id.total_assets_cny_text) TextView mTotalAssetsCnyText;
    @Bind(R.id.legal_tender_assets_text) TextView mLegalTenderAssetsText;
    @Bind(R.id.notification_view_flipper) ViewFlipper mNotificationViewFlipper;
    @Bind(R.id.assets_visibility_check_box) CheckBox mAssetsVisibilityCheckBox;
    @Bind(R.id.legal_tender_assets_cny_text) TextView mLegalTenderAssetsCnyText;
    @Bind(R.id.user_assets_state_layout) NetworkStateLayout mUserAssetsStateLayout;
    @Bind(R.id.performer_network_state_layout) NetworkStateLayout mNetworkStateLayout;

    private HomeViewModel mViewModel;
    private UserAssets.DataBean mUserAssets;
    private ImageAdvertsAdapter mAdvertsAdapter;
    private PersonalCenterViewModel mPersonalCenterViewModel;

    @Override
    protected int getLayoutID() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initActions() {
        mViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
        mPersonalCenterViewModel = ViewModelProviders.of(this).get(PersonalCenterViewModel.class);

        // 初始化广告
        initAdverts();

        // 用户信息
        initUserInfo();

        // 用户资产
        initUserAssets();

        // 初始化通知
        initNotification();

        // 初始化易量
        initVolumeBusiness();

        // 涨幅榜
        initAmountIncrease();

        // 控制资产可见性
        controlAssetsVisibility();

        // 点击登录
        mLoginView.setOnClickListener(LoginActivity::transitionLaunch);

        // 用户资产重新加载
        mUserAssetsStateLayout.setOnAnewRequestNetworkListener(this::initUserAssets);

        // 涨幅榜重点加载
        mNetworkStateLayout.setOnAnewRequestNetworkListener(this::initAmountIncrease);
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    private void controlAssetsVisibility() {
        mAssetsVisibilityCheckBox.setChecked(Androids.LocalConfig.getUserAssetsVisibility());
        mAssetsVisibilityCheckBox.setOnCheckedChangeListener((View, isChecked) -> {
            Androids.LocalConfig.setUserAssetsVisibility(isChecked);
            loadUserAssetsOntoView(isChecked);
        });
    }

    private void initUserInfo() {
        mPersonalCenterViewModel.userInfo().observe(this, resource -> {
            if (resource.state == Resource.Status.SUCCESS) {
                ImageViews.load(resource.source.getHead_scul(), mUserAvatarImage);
            }
        });
    }

    private void initAdverts() {
        GalleryLayoutManager layoutManager = new GalleryLayoutManager(GalleryLayoutManager.HORIZONTAL);
        layoutManager.attach(mAdvertsList, Integer.MAX_VALUE / 2);
        layoutManager.setItemTransformer(new ScaleTransformer());
        mAdvertsAdapter = new ImageAdvertsAdapter(BannerList.emptyBanner());
        mAdvertsList.setAdapter(mAdvertsAdapter);

        // 加载网络图片
        mViewModel.requestBanner().observe(this, result -> {
            CycleAdverts cycleAdverts = new CycleAdverts(mAdvertsList);
            getLifecycle().addObserver(cycleAdverts);
            mAdvertsAdapter.setAdverts(result);
            cycleAdverts.start();
        });
    }

    private void initUserAssets() {
        mHomeLoginLayout.setVisibility(Androids.LocalConfig.isLogin() ? GONE : VISIBLE);
        mUserAssetsLayout.setVisibility(!Androids.LocalConfig.isLogin() ? GONE : VISIBLE);
        mViewModel.requestUserAsserts().observe(this, resource -> {
            Resource.load(getContext(), resource, mUserAssetsStateLayout, result -> {
                //TransitionManager.beginDelayedTransition(mRootLayout);
                mUserAssetsStateLayout.showContentView();

                mUserAssets = resource.source;
                loadUserAssetsOntoView(Androids.LocalConfig.getUserAssetsVisibility());
            });
        });
    }

    private void initNotification() {
        mViewModel.requestAnnouncement().observe(this, announcements -> {
            for (AnnouncementList.DataBean.ListBean announcement : announcements) {
                String title = announcement.getTitle();
                TextView text = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.item_notification_text,
                        mNotificationViewFlipper, false);
                text.setText(title);
                mNotificationViewFlipper.addView(text);
            }

            //TransitionManager.beginDelayedTransition(mRootLayout);
            mAnnouncementLayout.setVisibility(VISIBLE);
        });
    }

    private void initVolumeBusiness() {
        mViewModel.requestTradingVolume().observe(this, result -> {
            mDayTurnoverText.setText(result.getDay());
            mWeekTurnoverText.setText(result.getWeek());
            mMonthTurnoverText.setText(result.getMonth());
        });
    }

    private void initAmountIncrease() {
        mViewModel.requestAmountIncrease().observe(this, resource -> {
            Resource.load(getContext(), resource, mNetworkStateLayout, result -> {
                //TransitionManager.beginDelayedTransition(mRootLayout);
                mNetworkStateLayout.showContentView();
                mPerformerList.setAdapter(new QuotationListAdapter(resource.source));
            });
        });
    }

    private void loadUserAssetsOntoView(boolean visibility) {
        UserAssets.DataBean userAssets;
        if (visibility) {
            userAssets = UserAssets.generateAssetsSymbol();
        } else {
            userAssets = mUserAssets;
        }

        mTotalAssetsText.setText(userAssets.getAll_balance());
        mTotalAssetsCnyText.setText(userAssets.getAll_cny() + " CNY");
        mCoinAssetsText.setText(userAssets.getTotal_worth_btc());
        mCoinAssetsCnyText.setText(userAssets.getTotal_worth_cny() + " CNY");
        mLegalTenderAssetsCnyText.setText(userAssets.getSum_cny2() + " CNY");
        mLegalTenderAssetsText.setText(userAssets.getSum2());
    }

    @Override
    protected void onVisible() {
        // 刷新状态栏
        ActivityBarHelper.setTransparentDarkColorStatus(getActivity());

        // 获取最新数据
        initAmountIncrease();
    }

    @Subscribe
    public void loginEvent(LoginEvent event) {
        initUserAssets();
        ImageViews.load(event.getPortrait(), mUserAvatarImage);
    }

    @Subscribe
    public void logoutEvent(LogoutEvent event) {
        mHomeLoginLayout.setVisibility(VISIBLE);
        mUserAssetsStateLayout.setVisibility(GONE);
    }

    @Subscribe
    public void userInfoChangeEvent(UserPortraitChangeEvent event) {
        ImageViews.load(event.portrait, mUserAvatarImage);
    }

    @Subscribe
    public void userAssetsVisibilityEvent(UserAssetsVisibilityEvent event) {
        mAssetsVisibilityCheckBox.setChecked(event.visibility);
    }

    @Subscribe
    public void userAssetsChnageEvent(UserAssetsChangeEvent event){
        initUserAssets();
    }

    public static Fragment newInstance() {
        return new HomeFragment();
    }
}
